<template>
  <div v-if="menu.visible !== false">
    <!-- 单个菜单项 -->
    <template v-if="!menu.children || menu.children.length === 0">
      <el-menu-item :index="menu.path" @click="handleMenuClick(menu)">
        <el-icon v-if="getIconComponent(menu.icon)" class="menu-icon">
          <component :is="getIconComponent(menu.icon)" />
        </el-icon>
        <template #title>
          <span>{{ menu.title || menu.name }}</span>
        </template>
      </el-menu-item>
    </template>

    <!-- 有子菜单的目录 -->
    <el-sub-menu v-else :index="menu.path">
      <template #title>
        <el-icon v-if="getIconComponent(menu.icon)" class="menu-icon">
          <component :is="getIconComponent(menu.icon)" />
        </el-icon>
        <span>{{ menu.title || menu.name }}</span>
      </template>
      <menu-item
        v-for="child in menu.children"
        :key="child.id"
        :menu="child"
      />
    </el-sub-menu>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import * as ElementPlusIcons from '@element-plus/icons-vue'

interface MenuItemProps {
  menu: {
    id: string
    name: string
    title?: string
    path: string
    icon?: string
    visible?: boolean
    menuType: string  // ✅ 修复：使用驼峰命名，与后端一致
    children?: MenuItemProps['menu'][]
  }
}

const props = defineProps<MenuItemProps>()
const router = useRouter()

const handleMenuClick = (menu: MenuItemProps['menu']) => {
  console.log('🖱️ [MenuItem] 菜单点击:', {
    title: menu.title,
    path: menu.path,
    menuType: menu.menuType
  })
  
  // ✅ 菜单类型判断：只支持 MENU
  if (menu.path && menu.menuType === 'MENU') {
    console.log('✅ [MenuItem] 跳转到:', menu.path)
    router.push(menu.path).catch(err => {
      console.error('❌ [MenuItem] 路由跳转失败:', err)
    })
  } else {
    console.warn('⚠️ [MenuItem] 菜单项不可点击:', {
      hasPath: !!menu.path,
      menuType: menu.menuType,
      expectedType: 'MENU'
    })
  }
}

// 获取图标组件
const getIconComponent = (iconName: string | undefined) => {
  if (!iconName) return null

  // 调试：输出图标信息
  // if (import.meta.env.MODE !== 'production') {
  //   console.log('🎨 MenuItem 图标调试:', {
  //     iconName,
  //     available: !!ElementPlusIcons[iconName as keyof typeof ElementPlusIcons],
  //     menuName: props.menu.name,
  //     menuTitle: props.menu.title
  //   })
  // }

  return ElementPlusIcons[iconName as keyof typeof ElementPlusIcons] || null
}
</script>

<style lang="scss" scoped>
.menu-icon {
  width: 20px !important;
  min-width: 20px !important;
  display: inline-flex !important;
  align-items: center !important;
  justify-content: center !important;
  margin-right: 12px !important;
  font-size: 16px !important;
  color: inherit !important;
}

// 确保图标在菜单项中垂直居中
:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  .menu-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
